import axios from 'axios'
import { getToken } from '@/utils/auth'
import { MessageBox, Message, Loading } from 'element-ui'
// import store from '@/store'
// import { getToken } from '@/utils/auth'
// create an axios instance
let loadingInstance = null

const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: '/', // url = base url + request url
  timeout: 60000
  // withCredentials: true, // send cookies when cross-domain requests
})

// request interceptor
service.interceptors.request.use(
  config => {
    loadingInstance = Loading.service({
      lock: true,
      text: '正在请求中...',
      spinner: 'el-icon-loading',
      background: 'rgba(0,0,0,.6)'
    })
    // if (store.getters.token) {
    //   // let each request carry token
    //   // ['X-Token'] is a custom headers key
    //   // please modify it according to the actual situation
    config.headers.Authorization = getToken()
    // }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    loadingInstance.close()
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    if (response.data) {
      const res = response.data
      loadingInstance.close()
      if (res) {
        return res
      }
      if (res.result !== 200) {
        this.$toast({
          message: res.errorMsg
        })
        return Promise.reject(res.errorMsg)
      } else {
        return res
      }
    } else {
      return response
    }
  },
  error => {
    console.log(error.message) // for debug
    loadingInstance.close()
    if (error.message.includes('timeout')) {
      Message({
        message: '请求超时！',
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      Message({
        message: error.errorMsg,
        type: 'error',
        duration: 5 * 1000
      })
    }

    return Promise.reject(error)
  }
)

export default service
